/*
 * @Date: 2023-03-26 09:05:56
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-26 10:28:32
 * @FilePath: \A19\backend\src\api\Get\ApiGetAllTInfo.ts
 */
import { ApiCall } from "tsrpc";
import { ReqGetAllTInfo, ResGetAllTInfo, info, safeStu } from "../../shared/protocols/Get/PtlGetAllTInfo";
import { Global } from "../../Global";

export default async function (call: ApiCall<ReqGetAllTInfo, ResGetAllTInfo>) {
    // TODO
    const p1 = Global.collection("selectCourses")
    .aggregate([
      {
        $match: {
          course: call.req.course,
        },
      },
      {
        $lookup: {
          from: "users",
          localField: "student",
          foreignField: "_id",
          as: "student",
        },
      },
      {
        $unwind: "$student",
      },
      { $replaceRoot: { newRoot: "$student" } },
    ])
    .toArray();

    const p2 = Global.collection("tests")
    .aggregate([
      {
        $match: {
          course: call.req.course,
          status: "published",
          _id:{
            $in:call.req.requiredTest
          }
        },
      },
      {
        $lookup: {
          from: "userTests",
          localField: "_id",
          foreignField: "test",
          as: "userTests",
        },
      },
      {
        $lookup: {
          from: "users",
          localField: "userTests.student",
          foreignField: "_id",
          as: "student",
        },
      },
      {
        $project: {
          course: false,
          startTime: false,
          endTime: false,
          questions: false,
          status: false,
          _id: false,

          "student.email": false,
          "student.password": false,
          "student.gender": false,
          "student.portrait": false,
          "student.role": false,
          "student.school": false,
          // 'student._id':false,

          "userTests.answers": false,
          "userTests.submitTime": false,
          "userTests.test": false,
          "userTests._id": false,
        },
      },
    ])
    .toArray();

    const ret = await Promise.all([p1, p2]);
    console.log(ret[1][0].userTests);
    call.succ({
      info: ret[1] as info[],
      students: ret[0] as safeStu[],
    });
}